//
//  SYJStatusDAL.swift
//  weibo
//
//  Created by 孙英建 on 16/4/28.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class SYJStatusDAL: NSObject {

    
    // 获取微博首页数据方法
    class func getHomeStatus(since_id: Int64, max_id: Int64, callback:(array: [[String: AnyObject]])->()){
        // 判断是否有数据在本地
        let result = checkoutCacheStatus(since_id, max_id: max_id)
        
        if result.count == 0{
            // 本地无数据从网络加载
            NetWorkTools.sharedTools.loadData(SYJUserAccountTools.sharedTools.access_token!, since_id: since_id, max_id: max_id) { (response, error) -> () in
                if error != nil{
                    print("请求失败")
                    callback(array: [])
                    return
                }
                
                guard let array = response?["statuses"] as? [[String: AnyObject]] else{
                    print("这不是一个数组")
                    callback(array: [])
                    return
                }
                
//                print("网络数据")
                callback(array: array)
                
                // 保存到数据库
                SYJStatusDAL.saveStatus(array)
            }

            
        }else{
            // 本地有数据直接回调
            callback(array: result)
//            print("缓存数据")
        }
        
        
    }
    
    
    // 保存微博缓存数据
    class func saveStatus(array: [[String: AnyObject]]){
        let userId = SYJUserAccountTools.sharedTools.userAccount!.uid!
        
        // 此语句标示如果相同的数据进行替换而不是插入
        let sql = "INSERT OR REPLACE INTO T_Status (statusId,status,userId) VALUES (?,?,?)"
        
        SYJSqlManager.sharedTools.queue.inTransaction { (db, rollback) -> Void in
            for dict in array {
                do{
                    let statusId = dict["id"] as! NSNumber
                    
                    let status = try! NSJSONSerialization.dataWithJSONObject(dict, options: [])
                    
                    try db.executeUpdate(sql, statusId, status, userId)
                    
                }catch{
                    print(error)
                    rollback.memory = true
                }
            }
        }
    }
    
    
    // 查询本地数据
    class func checkoutCacheStatus(since_id: Int64, max_id: Int64) -> [[String: AnyObject]] {
        // 第一次默认从网络加载
        if since_id == 0 && max_id == 0 {
            return []
        }
        
        let userId = SYJUserAccountTools.sharedTools.userAccount!.uid!
        
        var sql = "SELECT status FROM T_Status WHERE userId = \(userId) "
        
        // 下拉刷新
        if since_id > 0{
            sql += " AND statusId > \(since_id)"
        }
        
        // 上拉加载更多
        if max_id > 0 {
            sql += " AND statusId < \(max_id)"
        }
        
        // 限制查询20条并按时间排序
        sql += " ORDER BY statusId DESC LIMIT 20"
        
        var tempArr: [[String: AnyObject]] = [[String: AnyObject]]()
        
        SYJSqlManager.sharedTools.queue.inDatabase { (db) -> Void in
            do {
                
                let res = try db.executeQuery(sql)
                
                while res.next(){
                    let status = res.dataForColumn("status")
                    let dict = try! NSJSONSerialization.JSONObjectWithData(status, options: []) as! [String: AnyObject]
                    
                    tempArr.append(dict)
                }
                
            }catch{
                print(error)
            }
        }
        return tempArr
    }
  
    
    
    
}












